<template>
    <div class="app-container">
        <el-form :model="searchForm" inline ref="searchForm" style="position:relative;">
            <el-row>
                <el-col :span="20">
                    <el-form-item label="服务分类：" prop="serviceCategoryId">
                        <el-cascader clearable :options="serviceCategoryOpt" :props="optionProps" v-model="searchForm.serviceCategoryId" change-on-select></el-cascader>
                    </el-form-item>
                    <el-button type="primary" @click="init('search')" >查询</el-button>
                </el-col>
                <el-col :span="4">
                    <el-button @click="addClick" type="primary" style="position: absolute;right: 0;">添加服务</el-button>
                </el-col>
            </el-row>
        </el-form>
        <el-table :data="tableData" border style="width: 100%;margin-bottom: 20px;">
            <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
            <el-table-column label="logo" align="center">
                <template slot-scope="scope">
                    <!-- <img v-if="scope.row.logo" :src="scope.row.showpic" width="50" height="50" alt="/图片" @click="lookPic(scope.row.showpic)"> -->
                    <img v-if="scope.row.logo" :src="scope.row.logo" width="50" height="50" alt="/图片" @click="lookPic(scope.row.logo)">
                    <img v-else src="@/assets/image/default.png" width="50" height="50" alt="/图片">
                </template>
            </el-table-column>
            <el-table-column prop="name" label="名称" align="center"></el-table-column>
            <el-table-column prop="serviceLevelName" label="服务级别" align="center"></el-table-column>
            <el-table-column prop="serviceCategoryName" :formatter="serviceCategoryNameFun" label="服务分类" align="center"></el-table-column>
            <el-table-column prop="summary" label="摘要" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="sort" label="排序" align="center"></el-table-column>
            <el-table-column prop="enabled" :formatter="usingStatusFun" label="可用性" width="80" align="center"></el-table-column>
            <el-table-column prop="createTime" label="创建时间" align="center" width="160"></el-table-column>
            <el-table-column label="操作" width="240" align="center" fixed="right">
                <template slot-scope="scope">
                    <el-button @click.stop="editClick(scope.row)" type="primary" plain size="mini">编辑</el-button>
                    <el-button @click.stop="statusClick(scope.row)" type="warning" plain size="mini">{{(scope.row.enabled == 1) ? '禁用' : '启用'}}</el-button>
                    <el-button @click.stop="delClick(scope.row)" type="danger" plain size="mini">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination @current-change="getList" layout="total, prev, pager, next, jumper" :total="pageData.totalElements"></el-pagination>
        <!-- 弹框 -->
        <el-dialog :visible.sync="showDialog" width="800px">
            <el-form ref="dataForm" :rules="rules" :model="dataForm" label-position="left" label-width="120px" style="margin: 0px 50px;">
                <el-form-item label="Logo：" prop="logo">
                    <el-upload class="avatar-uploader" action="" :http-request="UploadImage" :show-file-list="false" :before-upload="beforeAvatarUpload" >
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" width="100%">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="名称：" prop="name">
                    <el-input v-model="dataForm.name" placeholder="必填项。请输入长度为1-30位由中英文数字-_.组成的名称" maxlength="30"></el-input>
                </el-form-item>
                <el-form-item label="服务级别：" prop="serviceLevelId">
                    <el-select v-model="dataForm.serviceLevelId" placeholder="必选项。请选择服务级别" style="width: 100%;">
                        <el-option v-for="item in serviceLevelOpt" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="服务分类：" prop="serviceCategoryId">
                    <el-cascader clearable :options="serviceCategoryOpt" :props="optionProps" v-model="serviceCategoryId" change-on-select style="width: 100%;"></el-cascader>
                </el-form-item>
                <el-form-item label="摘要：" prop="summary">
                    <el-input v-model="dataForm.summary" type="textarea" :rows="4" placeholder="请输入摘要"></el-input>
                </el-form-item>
                <el-form-item label="描述：" prop="description">
                    <quill-editor v-model="dataForm.description" ref="myQuillEditor" :options="editorOption" placeholder="请输入描述"></quill-editor>
                </el-form-item>
                <el-form-item label="顺序值：" prop="sort">
                    <el-input v-model="dataForm.sort" type="number" placeholder="请输入顺序值"></el-input>
                </el-form-item>
                <el-form-item label="可用性：" prop="enabled">
                    <el-select v-model="dataForm.enabled" placeholder="请选择可用性" style="width: 100%;">
                        <el-option v-for="item in usingStatusOpt" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="addSubmit('dataForm')" type="primary">保存</el-button>
                    <el-button @click="cancelClick('dataForm')">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 放大图片 -->
        <el-dialog :visible.sync="dialogPicVisible" text-center>
            <img :src="nowBigPic" alt="" width="100%">
        </el-dialog>
    </div>
</template>
<script>
import { findServiceCategory } from '@/api/service/service-category'
import { findServiceLevel } from '@/api/service/service-level'
import { addService, findService, editService, enableService, detailService, delService } from '@/api/service/customize-service-level'
import { isNameValidate, isvalidInitNumber } from '@/utils/validate'
import { uploadPic, getPic } from '@/api/uploadPic'
export default {
    name: 'Service',
    data() {
        var NameValidate=(rule, value,callback)=>{
            if(isNameValidate(value)){
                callback()
            }else{
                callback(new Error('请输入长度为1-30位由中英文数字-_.组成的名称'))
            }
        }
        var InitNumber=(rule, value,callback)=>{
            if(value){
                if(isvalidInitNumber(value)){
                    callback()
                }else{
                    callback(new Error('请输入整数'))
                }
            }else{
                callback()
            }
        }
        return{
            tableData: [],
            nowTit: '',
            nowId: '',
            showDialog: false,
            dataForm: {
                name: '',
                serviceLevelId: '',
                serviceCategoryId: '',
                summary: '',
                description: '',
                sort: '',
                enabled: 1,
                logo: '',
            },
            rules: {
                name: [
                    { required: true, message: '请输入', trigger: 'blur' },
                    {  trigger: 'blur', validator: NameValidate }
                ],
                serviceLevelId: [
                    { required: true, message: '请选择', trigger: 'change' }
                ],
                sort: [
                    { trigger: 'blur', validator: InitNumber }
                ],
            },
            searchForm: {serviceCategoryId: []},
            nowPage: 0,
            pageSize: 10,
            imageUrl: '',
            formData: {},
            popStatus: 0,  //0为添加，1为修改
            pageData: {},
            usingStatusOpt: [
                {label: '启用', value: 1},
                {label: '禁用', value: 0}
            ],
            editorOption: {
                // placeholder设置提示词
                placeholder: '请输入正文......',
                // modules设置工具栏
                modules: {
                    toolbar: [
                        ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
                        ["blockquote", "code-block"], // 引用  代码块
                        [{ header: 1 }, { header: 2 }], // 1、2 级标题
                        [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
                        [{ script: "sub" }, { script: "super" }], // 上标/下标
                        [{ indent: "-1" }, { indent: "+1" }], // 缩进
                        [{'direction': 'rtl'}],                         // 文本方向
                        [{ size: ["small", false, "large", "huge"] }], // 字体大小
                        [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
                        [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
                        [{ font: [] }], // 字体种类
                        [{ align: [] }], // 对齐方式
                        ["clean"], // 清除文本格式
                        ["link", "image", "video"] // 链接、图片、视频
                    ]
                }
            },
            serviceLevelOpt: [],
            serviceCategoryOpt: [],
            optionProps: {
                value: 'id',
                label: 'name',
                children: 'children'
            },
            serviceCategoryId: [],
            dialogPicVisible: false,
            nowBigPic: '',
        }
    },
    methods: {
        //默认函数
        init(params){
            const _this = this;
            if(params == 'search'){
                _this.nowPage = 0
            }
            let sid = '';
            if(_this.searchForm.serviceCategoryId.length > 0){
                sid = _this.searchForm.serviceCategoryId[_this.searchForm.serviceCategoryId.length - 1];
            }
            _this.tableData = [];
            //获取列表信息
            findService(this.nowPage, this.pageSize,sid).then(response => {
                if(response.code == 200){
                    _this.pageData = response.object
                    _this.tableData = response.object.content
                    // if(response.object.content){
                    //     if(response.object.content.length>0){
                    //         for (const key in response.object.content) {
                    //             //处理图片
                    //             if(response.object.content[key].logo){
                    //                 getPic(response.object.content[key].logo).then(res => {
                    //                     if(res.code == 200){
                    //                         response.object.content[key].showpic = res.object;
                    //                         _this.tableData.push(response.object.content[key]);
                    //                     }else{
                    //                         this.$message.error(res.message);
                    //                     }
                    //                 })
                    //             }else{
                    //                 response.object.content[key].showpic = '';
                    //                 _this.tableData.push(response.object.content[key]);
                    //             }
                    //         }
                    //     }else{
                    //         _this.tableData = []
                    //     }
                    // }
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        serviceLevelList(){
            const _this = this;
            //获取列表信息
            findServiceLevel(0, 10000).then(response => {
                if(response.code == 200){
                    _this.serviceLevelOpt = response.object.content;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        serviceCategoryList(){
            const _this = this;
            //获取列表信息
            findServiceCategory(0, 10000).then(response => {
                if(response.code == 200){
                    _this.serviceCategoryOpt = _this.getTreeData(response.object.content);
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //递归
        getTreeData(data){
            for(var i=0;i<data.length;i++){
                if((data[i].children == null) || (data[i].children.length<1)){
                    data[i].children=undefined;
                }else {
                    this.getTreeData(data[i].children);
                }
            }
            return data;
        },
        //添加
        addClick(){
            this.popStatus = 0;
            this.showDialog = true;
            this.dataForm.name = '';
            this.dataForm.serviceLevelId = '';
            this.dataForm.serviceCategoryId = '';
            this.serviceCategoryId = [];
            this.dataForm.summary = '';
            this.dataForm.description = '';
            this.dataForm.sort = '';
            this.dataForm.enabled = 1;
            this.dataForm.logo = '';
            this.imageUrl = '';
            if(this.dataForm.id){
                delete this.dataForm.id;
            }
        },
        //提交添加
        addSubmit(formName){
            let _this = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    //提交
                    if(_this.serviceCategoryId.length != 0){
                        _this.dataForm.serviceCategoryId = _this.serviceCategoryId[_this.serviceCategoryId.length - 1];
                    }else{
                        _this.dataForm.serviceCategoryId = '';
                        this.$message.warning('请选择服务分类');
                        return
                    }
                    if(_this.popStatus == 0){  //添加
                        addService(_this.dataForm).then(response => {
                            if(response.code == 200){
                                this.$message.success(response.message);
                                _this.init();
                                _this.showDialog = false;
                            }else{
                                this.$message.error(response.message);
                            }
                        })
                    }else if(_this.popStatus == 1){  //修改
                        _this.dataForm.id = _this.nowId;
                        editService(_this.dataForm).then(response => {
                            if(response.code == 200){
                                this.$message.success(response.message);
                                _this.init();
                                _this.showDialog = false;
                            }else{
                                this.$message.error(response.message);
                            }
                        })
                    }
                    
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //删
        delClick(row){
            let _this = this;
            this.$confirm('确定删除 '+row.name+' 吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //删除
                delService(row.id).then(response => {
                    if(response.code == 200){
                        this.$message.success(response.message);
                        _this.init();
                    }else{
                        this.$message.error(response.message);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });          
            });
        },
        //编辑
        editClick(row){
            this.popStatus = 1;
            this.nowId = row.id;
            this.dataForm.name = row.name;
            this.dataForm.serviceLevelId = row.serviceLevelId;
            this.dataForm.serviceCategoryId = row.serviceCategoryId;
            //处理服务分类id
            if(row.serviceCategoryList){
                let arr = [];
                for (const key in row.serviceCategoryList) {
                    if (row.serviceCategoryList.hasOwnProperty(key)) {
                        const element = row.serviceCategoryList[key];
                        arr.push(element.id);
                    }
                }
                this.serviceCategoryId = arr;
            }
            this.dataForm.summary = row.summary;
            this.dataForm.description = row.description;
            this.dataForm.sort = row.sort;
            this.dataForm.enabled = row.enabled;
            // if(row.logo){
            //     this.imageUrl = row.showpic;
            // }else{
            //     this.imageUrl = '';
            // }
            this.imageUrl = row.logo
            this.showDialog = true;
        },
        //自定义上传
        UploadImage(param){
            const _this = this;
            //上传图片
            let formData = new FormData();
            formData.append('photoFile', param.file);
            formData.append('dir', 'Service');
            formData.append('fileType', '1');
            uploadPic(formData).then(response => {
                if(response.code == 200){
                    _this.dataForm.logo = response.object.saveImage;
                    this.imageUrl = response.object.showImage;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //准备上传
        beforeAvatarUpload(file){
            const isJPG = file.type;
            const isLt2M = file.size / 1024 / 1024 < 5;
            if(((isJPG === 'image/jpeg') || (isJPG === 'image/png') || (isJPG === 'image/jpg') || (isJPG === 'image/gif') || (isJPG === 'image/JPEG') || (isJPG === 'image/PNG') || (isJPG === 'image/JPG') || (isJPG === 'image/GIF')) == false){
                this.$message.error('上传图片只能是 jpeg、png、jpg、gif 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 5MB!');
            }
            return isJPG && isLt2M;
        },
        //取消
        cancelClick(formName){
            this.showDialog = false;
            this.$refs[formName].resetFields();
        },
        //启用禁用
        statusClick(row){
            let usingStatus,isUsing;
            if(row.enabled == 1){  //启用状态
                usingStatus = 0;
                isUsing = '禁用';
            }else{
                usingStatus = 1;
                isUsing = '启用';
            }
            let _this = this;
            this.$confirm('确定修改状态为 '+ isUsing +' 吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //启用禁用
                enableService({id: row.id, enabled: usingStatus}).then(response => {
                    if(response.code == 200){
                        this.$message.success(response.message);
                        _this.init();
                    }else{
                        this.$message.error(response.message);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });          
            });
        },
        //分页
        getList(val) {
            this.nowPage = val - 1;
            this.init();
        },
        usingStatusFun(row){
            if(row.enabled == 1){
                return '启用'
            }else if(row.enabled == 0){
                return '禁用'
            }
        },
        serviceCategoryNameFun(row){
            //处理所属部门name
            if(row.serviceCategoryList){
                let arr = '';
                for (const key in row.serviceCategoryList) {
                    if (row.serviceCategoryList.hasOwnProperty(key)) {
                        const element = row.serviceCategoryList[key];
                        arr += element.name + ' / '
                    }
                }
                return arr.substr(0,arr.length - 3)
            }
        },
        //放大图片
        lookPic(pic){
            this.nowBigPic = pic;
            this.dialogPicVisible = true;
        },
    },
    mounted(){
        this.init();
        this.serviceLevelList();
        this.serviceCategoryList();
    }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>